<template>
  <div class="login">
    <div class="login-toggle" @click="handleClickTypes()">
      <Icon
        v-if="state.typeKey === state.types[1].name"
        class="login-phone"
        size="80"
        type="ios-phone-portrait"
      />
      <qrcode class="login-code" />
    </div>
    <div class="login-input" v-if="state.typeKey === state.types[0].name">
      <h3>欢迎使用 宝贝印记</h3>
      <div style="height: 10px"></div>

      <!-- 短信和密码切换 -->
      <ul class="image-box-tab">
        <li
          v-for="item in state.tabs"
          :key="item.name"
          :class="item.name === state.active && 'active'"
          @click="handleClickTab(item.name)"
        >
          {{ item.label }}
        </li>
        <div class="block" :style="{ left: state.left }"></div>
      </ul>
      <div style="height: 10px"></div>

      <!-- 短信登录 -->
      <div
        class="login-input-message"
        v-if="state.active === state.tabs[0].name"
        @click="handleClickTab(state.tabs[0].name)"
      >
        <div class="input-box">
          <input v-model="state.phone" class="input" placeholder="请输入手机号" />
        </div>
        <div class="input-box">
          <input v-model="state.code" class="input" placeholder="验证码" />
          <label v-if="!state.smsCount" class="input-box-send" @click="handleSendMsg">发送</label>
          <CountDown
            v-else
            :target="state.time"
            @on-end="handleTimeEnd"
            v-font="14"
            style="padding: 0 10px; color: var(--color-text-placeholder)"
            :format="formatTime"
          />
        </div>
      </div>
      <!-- 密码登录 -->
      <!-- <div
        class="login-input-code"
        v-if="state.active === state.tabs[1].name"
        @click="handleClickTab(state.tabs[1].name)"
      >
        <div class="input-box">
          <input class="input" placeholder="请输入手机号" />
        </div>
        <div class="input-box">
          <input
            class="input"
            :type="`${state.showPassword ? 'input' : 'password'}`"
            placeholder="请输入密码"
          />
          <Icon
            class="input-box-password"
            :type="`${state.showPassword ? 'md-eye' : 'md-eye-off'}`"
            @click="handleClickPassword()"
          />
        </div>
      </div> -->

      <!-- 确认 -->
      <div class="login-btn" @click="handleLogin()">登录</div>
      <div class="login-pricy">
        <input type="checkbox" v-model="state.checkbox" />
        &nbsp; 阅读并同意
        <a>隐私政策</a>
      </div>
    </div>
    <div class="login-code" v-if="state.typeKey === state.types[1].name">
      <h2 class="login-code-title">微信安全登录</h2>
      <img class="login-code-qr" :src="state.weCode" @click="fetchCreateWxLoginErCode" />
      <h4>
        注册代表同意
        <a>隐私政策</a>
      </h4>
    </div>
  </div>
</template>

<script setup name="Tools">
import { createWxLoginErCode, mobileLogin, sendSmsCodeByLogin } from '@/api/login';
import { to } from '@/utils/await-to.js';
import { Message } from 'view-ui-plus';
import { setLocal } from '@/utils/local';
import { createQRCode } from '@/utils/tools';
import qrcode from '@/assets/icon/tools/qrcode.svg';
import { useRouter } from 'vue-router';
const router = useRouter();

const state = reactive({
  left: '5px',
  showPassword: false,
  // 加载微信二维码链接
  weCodeLoading: false,
  // 短信发送成功，倒计时中
  smsCount: false,
  time: '',
  weCode: '',
  typeKey: 'account',
  types: [
    {
      name: 'account',
      label: '账号密码',
    },
    {
      name: 'qr',
      label: '微信扫码',
    },
  ],
  active: 'message',
  tabs: [
    {
      name: 'message',
      label: '短信登录',
    },
    // {
    //   name: 'password',
    //   label: '密码登录',
    // },
  ],
  phone: '',
  code: '',
  checkbox: false,
});

const handleClickTypes = () => {
  if (state.typeKey === state.types[0].name) {
    state.typeKey = state.types[1].name;
    fetchCreateWxLoginErCode();
  } else if (state.typeKey === state.types[1].name) {
    state.typeKey = state.types[0].name;
  }
};

const handleClickTab = (name) => {
  state.active = name;

  if (name === 'message') {
    state.left = '5px';
  } else if (name === 'password') {
    state.left = '79px';
  }
};

// const handleClickPassword = (flag) => {
//   state.showPassword = !state.showPassword;
// };

// 发送验证码
const handleSendMsg = async () => {
  const [err, res] = await to(
    sendSmsCodeByLogin({
      phone: state.phone,
    })
  );

  if (err) return Message.warning(err.msg || '获取验证码失败');

  const { data } = res || {};
  const { code, msg } = data || {};

  if (code !== 200) return Message.warning(msg || '获取验证码失败');
  Message.success('验证码已发送');
  // 开始倒计时
  state.smsCount = true;
  state.time = new Date().getTime() + 60000;
};

// 倒计时结束
const handleTimeEnd = () => {
  state.smsCount = false;
};

// 手机号验证码登录
const handleLogin = async () => {
  if (!state.checkbox) return Message.warning('请勾选协议');

  const [err, res] = await to(
    mobileLogin({
      phone: state.phone,
      code: state.code,
    })
  );

  if (err) return Message.warning(err.msg || '登录失败');

  console.log(err, res);
  const { data } = res || {};
  const { code, msg, data: token } = data || {};

  if (code !== 200 || !token) return Message.warning(msg || '登录失败');

  setLocal('token', token);
  gotoHome();
};

const fetchCreateWxLoginErCode = async () => {
  state.weCodeLoading = true;
  const [err, res] = await to(
    createWxLoginErCode({
      redirectUrl: 'http://localhost:3000/#/login',
    })
  );
  state.weCodeLoading = false;
  console.log(err, res);
  if (err) {
    return Message.warning(err?.msg || '获取微信二维码异常');
  }

  const { data } = res || {};
  const { code, msg, data: src } = data || {};

  if (code !== 200) {
    return Message.warning(msg || '获取微信二维码异常');
  }

  const [imgErr, url] = await to(createQRCode(src));
  if (imgErr) return Message.warning(msg || '获取微信二维码异常');

  state.weCode = url;
  console.log(url);
};

const gotoHome = () => {
  // router.push('/')
  router.replace('/');
};

function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}
const formatTime = (time) => {
  const hours = 60 * 60 * 1000;
  const minutes = 60 * 1000;

  const h = Math.floor(time / hours);
  const m = Math.floor((time - h * hours) / minutes);
  const s = Math.floor((time - h * hours - m * minutes) / 1000);

  return `${fixedZero(s)}`;
};

onMounted(async () => {
  console.log('login');
});
</script>

<style scoped lang="less">
.login {
  position: relative;
  left: 50%;
  top: 50%;
  border-radius: 10px;
  width: 400px;
  height: 464px;
  border: 1px solid var(--color--border-float);
  background-color: var(--color--bg-float);
  margin-left: -200px;
  margin-top: 100px;
  overflow: hidden;
  padding: 0 70px;

  display: flex;
  flex-direction: column;
  justify-content: center;

  .login-toggle {
    position: absolute;
    top: 0;
    right: 0;
    width: 64px;
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--background-primary-color);
    transform: skewY(45deg);
    transform-origin: top right;
    cursor: pointer;
    border-top-right-radius: 10px;
    overflow: hidden;

    .login-phone,
    .login-code {
      color: var(--primary-color);
      position: relative;
      transform: skewY(315deg);
      top: 32px;
    }

    .login-phone {
      top: 45px;
    }

    svg {
      width: 50px;
      height: 50px;
      fill: var(--primary-color);
    }
  }

  .login-btn {
    width: 100%;
    background-color: var(--primary-color);
    color: var(--color-text-primary);
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 14px;
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }

  .login-code {
    display: flex;
    flex-direction: column;
    align-items: center;

    .login-code-title {
      text-align: center;
      margin-bottom: 30px;
    }

    .login-code-qr {
      display: inline-block;
      width: 200px;
      height: 200px;
      background-color: var(--background-primary-color);
      border-radius: 8px;
      overflow: hidden;
      cursor: pointer;
    }

    a {
      color: var(--primary-color);
    }
  }

  .image-box-tab {
    width: 160px;
    height: 40px;
    border-radius: 6px;
    background-color: var(--background-primary-color);
    display: flex;
    align-items: center;
    justify-content: start;
    position: relative;

    li {
      width: 75px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: #999;
      cursor: pointer;
      position: relative;
      z-index: 2;
      margin-left: 5px;

      &.active {
        color: var(--primary-color);
        font-weight: bold;
      }
    }

    .block {
      width: 75px;
      height: 28px;
      border-radius: 6px;
      background-color: var(--color--bg-float);
      box-shadow: var(--shadow-m);
      position: absolute;
      content: ' ';
      top: 7px;
      z-index: 1;
      transition: left 0.3s ease-in-out;
    }
  }

  .input-box {
    width: 100%;
    display: flex;
    align-items: center;
    margin-top: 6px;
    background-color: var(--background-primary-color);
    border-radius: 6px;
    overflow: hidden;
    border: 1px solid var(--primary-color);

    input {
      border: none;
      outline: none;
      flex: 1;
      height: 40px;
      padding: 0 12px;
      background-color: transparent;

      &::placeholder {
        color: var(--color-text-placeholder);
        font-size: 12px;
      }

      &::-webkit-input-placeholder {
        color: var(--color-text-placeholder);
        font-size: 12px;
      }
    }

    .input-box-password {
      cursor: pointer;
      color: var(--color-text-placeholder);
      padding: 0 10px;
    }

    .input-box-send {
      font-size: 14px;
      color: var(--primary-color);
      padding: 0 10px;
      cursor: pointer;
    }
  }

  .login-pricy {
    display: flex;
    align-items: center;
    margin-top: 6px;
    font-size: 12px;
    color: var(--color-text-secondary);

    input {
      /* 隐藏原生复选框 */
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;

      /* 自定义样式 */
      width: 14px;
      height: 14px;
      border: 1px solid var(--primary-color);
      border-radius: 3px;
      position: relative;
      outline: none;
      margin-right: 3px;
      cursor: pointer;

      /* 选中状态 */
      &:checked {
        background-color: var(--primary-color); /* 选中的颜色 */
      }

      /* 可以添加伪元素来显示一个“勾”或其他图标 */
      &:checked::after {
        content: ' '; /* 内容可以是图片或其他图标 */
        position: absolute; /* 绝对定位 */
        left: 2px; /* 调整位置 */
        top: 3px; /* 调整位置 */
        width: 8px; /* 图标宽度 */
        height: 4px; /* 图标高度 */
        border-left: 2px solid var(--color-text-primary);
        border-bottom: 2px solid var(--color-text-primary);
        transform: rotate(-45deg);
      }

      /* 禁用状态 */
      &:disabled {
        background-color: var(--color-text-placeholder); /* 禁用时的颜色 */
      }
    }

    a {
      color: var(--primary-color);
    }
  }
}
</style>
